<template>
  <div>
    <!--  面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--  卡片视图区-->
    <el-card>
      <!--      搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList"
                    @change="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList">sousuo</el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表区  stripe隔行变色-->
      <el-table  :data="usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <!--        prop  指向具体属性值  值是网络请求里面的数据值-->
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <!--            {{scope.row}}  作用域插槽  通过slot-scope  接收了当前作用域的数据scope   scope.row拿到当前这一行的数据                                -->
            <el-switch
                v-model="scope.row.mg_state" @change="userchang(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!--            修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!--            删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row.id)"></el-button>
            <!--            分角色按钮-->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" size="mini" @click="fenpeijiaose(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--尾部页数-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </el-card>
    <!--    添加用户对话框-->
    <el-dialog @close="guanbichongzhi"
               title="添加用户"
               :visible.sync="dialogVisible"
               width="50%"
               :before-close="handleClose"
    >
      <!--      对话框内容主体区域-->
      <el-form :model="addfrom" :rules="addfromrules" ref="addFromRef" label-width="70px">

        <el-form-item label="姓名" prop="username">
          <el-input v-model="addfrom.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addfrom.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addfrom.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addfrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部按钮-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--  修改用户对话框-->
    <el-dialog @close="guanbi"
               title="修改用户"
               :visible.sync="editvisible"
               width="50%"
               :before-close="handleClose">
      <!--          修改用户的信息-->
      <el-form :model="adit" :rules="aditrules" ref="ruleForm" label-width="70px">
        <el-form-item label="姓名">
          <el-input v-model="adit.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adit.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="adit.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editvisible = false">取 消</el-button>
        <el-button type="primary" @click="aditinfo">确 定</el-button>
      </span>
    </el-dialog>
<!--    分配角色的对话框-->
    <el-dialog
        title="分配角色"
        :visible.sync="fenpei"
        width="50%"
        @close="setRoleDialogClosed"
        :before-close="handleClose">
<el-form>
  <div>
    <p>当前的用户: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{userinfo.username}}</p>
    <p>当前的角色: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{userinfo.role_name}}</p>
    <p>分配新角色:
      <el-select style="margin-left: 10px" v-model="selectedRoleID" placeholder="请选择">
        <el-option
            v-for="item in jiaoselist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
        </el-option>
      </el-select>
    </p>

  </div>

</el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="fenpei = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    //验证邮箱的规则
    var checkEmails = (rule, value, callback) => {
      //验证邮箱的正则表达式
      const reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (reg.test(value)) {
        //合法的邮箱  放行用后面callback这个参数
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    //验证手机号规则
    var mobiles = (rule, value, callback) => {
      const phone = /^[1][3,4,5,7,8][0-9]{9}$/;

      if (phone.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的11位手机号'))
    }
    return {
      //  获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,//当前页码1页
        pagesize: 2//每页显示条数2条
      },
      usersList: [],
      total: 0,
      //控制添加用户对话框的显示与隐藏
      dialogVisible: false,
      //添加用户表单数据
      addfrom: {
        username: '',
        password: '',
        email: '',
        mobile: '',

      },
      //添加表单验证规则对象
      addfromrules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmails, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: mobiles, trigger: 'blur'}
        ]
      },
      //  修改用户对话框
      editvisible: false,
      //分配角色对话框默认关闭
      fenpei:false,
      adit: {},
      //需要被分配角色的用户信息
      userinfo:{},
      //所有角色列表的数据
      jiaoselist:[],
      selectedRoleID:'',//分配角色下拉选项
      //  修改用户的验证
      aditrules: {
        email: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {validator: checkEmails, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: mobiles, trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户量列表失败')
      }
      this.usersList = res.data.users
      this.total = res.data.total

      console.log(res)
    },
    //监听pagesize改变的事件  条/页
    handleSizeChange(pagesize) {
      console.log(pagesize)
      this.queryInfo.pagesize = pagesize    //点击几条每页的时候  把最新的数据给queryInfo.pagesize  这样才能同步   再从新执行网络请求
      this.getUsersList()
    },
    //监听当前页
    handleCurrentChange(pagenum) {
      console.log(pagenum)
      this.queryInfo.pagenum = pagenum
      this.getUsersList()
    },
    //监听swith开关状态的改变
    async userchang(userinfo) {  //userinfo接收所有的状态数据  由插槽语法传过来的
      console.log(userinfo)
      // 拿到状态之后立即发起网络请求  然后调用接口   把状态同步到服务器中
      const {data: res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      // this.userinfo.mg_state = userinfo.mg_state
      this.$message.success('更新用户数据成功')
      console.log(res)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });

    },
    //关闭对话框重置清空
    guanbichongzhi() {
      //通过$refs这个对象能找到  addfromref 这个属性
      this.$refs.addFromRef.resetFields()
    },
    //点击确定预校验
    addUser() {
      //valid  接收校验结果
      this.$refs.addFromRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const {data: res} = await this.$http.post('users', this.addfrom)
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        //成功之后让对话框隐藏
        this.dialogVisible = false
        // 然后重新获取用户列表数据
        this.getUsersList()
      })
    },
    //点击修改按钮  修改用户信息
    async showEditDialog(id) {
      console.log(id)
      const {data: res} = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.adit = res.data
      this.editvisible = true
    },
    //修改用户信息  对话框关闭时   重置对话框
    guanbi() {
      this.$refs.ruleForm.resetFields()
    },
    //用户修改信息  确定按钮  点击确定修改的按钮  发送网络请求
    aditinfo() {
      this.$refs.ruleForm.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('修该用户信息失败')
        }
        const {data: res} = await this.$http.put('users/' + this.adit.id, {
          email: this.adit.email,
          mobile: this.adit.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修该用户信息失败')
        }

        //关闭对话框
        this.editvisible = false
        //从新获取数据
        this.getUsersList()
        this.$message.success('修改用户信息成功')
      })

    },
    //点击删除
     async del(id) {
      console.log(id)
       // confirmResult  用来接收 $confirm 这里面的返回数的    confirm挂载到了vue原型上 通过this可以弹出对话框
     const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err =>err)  // catch(err =>err) 把错误信息返回给 confirmResult
      console.log(confirmResult)
       if (confirmResult !== 'confirm'){
         return this.$message.error('已取消删除')
       }
       const {data:res} = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
       this.getUsersList()
    }
,
    //分配角色
    async fenpeijiaose (row) {

      this.userinfo = row
      //在展示对话框之前获取所有角色的列表
    const {data:res} = await this.$http.get("roles")
      // console.log(res)
      if (res.meta.status !==200){
        return this.$message.error('获取角色列表失败')
      }
      this.$message.success('获取角色列表成功')
      this.jiaoselist = res.data
      this.fenpei = true

    },
    //分配角色确定按钮
    async saveRoleInfo () {
      if (!this.selectedRoleID){
       return this.$message.error('请选择要分配的角色')
      }
    const {data:res} =await this.$http.put(`users/${this.userinfo.id}/role`,{rid:this.selectedRoleID})
      if (res.meta.status !==200){
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.getUsersList()
      this.fenpei = false

    },
    //监听分配校色对话框 关闭时间
    setRoleDialogClosed () {
      this.selectedRoleID = ''
      this.userinfo = {}
    }

  }
}
</script>

<style scoped>

</style>